<template>
  <BusinessHeader>
    用户登录
  </BusinessHeader>
  <div class="wrapper">
    <el-form
        ref="ruleFormRef"
        status-icon
        label-width="120px"
        class="demo-ruleForm"
        :model="loginForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input type="text" v-model="loginForm.userName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginForm.userPassword" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="login">登录</el-button>
        <el-button type="primary" @click="toRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
  <TabBar></TabBar>
</template>

<script setup>
import BusinessHeader from "@/components/common/HeaderPart";
import TabBar from '@/components/common/TabBar'
import router from "@/router";
import {onMounted, ref} from "vue";
import request from "@/utils/request";
// import {useRoute} from "vue-router";
onMounted(() => {
})
let userPassing = JSON.parse(localStorage.getItem("userPassing"))
const loginForm = ref({userName: userPassing?.username, userPassword: userPassing?.password})
const user = ref({})
const businessInfo = ref({})

function toRegister() {
  router.push('/RegisterPart')
}

async function login() {
  let data = new FormData()
  data.append("username", loginForm.value.userName)
  data.append("password", loginForm.value.userPassword)
  // 登录
  let res = await request({url: '/login', method: 'POST', data: data})
  console.log(res)
  if (res.flag && res.data.userInfo) {
    const {userInfo, token} = res.data
    user.value = userInfo
    //  存token
    localStorage.setItem('token', token)
    // 存账号密码,不影响啥
    localStorage.setItem('userPassing',
        JSON.stringify({
          username: user.value.userName,
          password: user.value.userPassword,
        }));
    localStorage.setItem('isLogin', 'true')
    localStorage.setItem('userLoginAll', JSON.stringify(user.value))
    router.push({path: "/MyInfo"})
    return
  }
  if (res.flag && res.data.business){
    const {business, token} = res.data
    businessInfo.value = business
    //  存token
    localStorage.setItem('token', token)
    localStorage.setItem('businesspassing',
        JSON.stringify({
          username: businessInfo.value.businessName,
          password: businessInfo.value.businessPassword,
        }));
    localStorage.setItem('isLogin', 'true')
    localStorage.setItem('businessInfo', JSON.stringify(businessInfo.value))
    router.push({path: "/business-home"})
  }
}
</script>

<style scoped>
.wrapper {
  margin-top: 5rem;
  margin-left: 3rem;
  margin-right: 3rem;
}

:deep(.el-form-item__label) {
  width: 75px !important;
}

.button {
  height: 2rem;
  width: 100%;
}
</style>
